// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })
  const db = cloud.database()
  const wxContext = cloud.getWXContext()
  app.router("verifyToken", async (ctx, next) => {
    const r = await db.collection("token").get()
    if (r.data[0].token === event.token) {
      const res = await db.collection('users')
        .where({
          _openid: wxContext.OPENID
        })
        .update({
          data: {
            role: "admin"
          }
        })
      ctx.body = {
        code: 200,
        result: res.stats.updated
      }
    } else {
      ctx.body = {
        code: 403
      }
    }
  })
  app.router("verifyAdmin", async (ctx, next) => {
    const res = await db.collection('users')
      .where({
        _openid: wxContext.OPENID
      }).get()
    ctx.body = {
      code: 200,
      result: res.data[0].role === 'admin'
    }

  })

  return app.serve()
}